import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:appflutterhomeschool/api/api_service.dart';
import 'package:appflutterhomeschool/api/dio_utils.dart';
import 'package:appflutterhomeschool/common/common.dart';
import 'package:appflutterhomeschool/model/student_information_model.dart';
import 'package:appflutterhomeschool/route/application.dart';
import 'package:appflutterhomeschool/route/routes.dart';
import 'package:appflutterhomeschool/ui/dialogs/prompt_dialog_widgets.dart';
import 'package:appflutterhomeschool/utils/sp_util.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:fluwx/fluwx.dart' as fluwx;

///用户：Nine Tailed Fox
///时间：2020/6/10
///邮箱：1037438704@qq.com
///功能：主页面

class LoginViewModel extends ChangeNotifier {
  BuildContext me;

  //是否显示密码
  bool obscureText = true;

  //手机号码
  TextEditingController phoneText = TextEditingController();

  TextEditingController passwordText = TextEditingController();

  LoginViewModel(this.me);

  bool isWeChatInstalled = true;

  initView() {
    //判断是否是第一次进入
    // 延时1s执行返回
    Future.delayed(Duration(seconds: 3), () {
      if (!SpUtil.getBool('login') ?? true) {
        PromptDialogWidgets(me).showPromptDialog(
          title: '温馨提示',
          content: '欢迎使用XXXX，在你使用的时候，需要连接网络，产生的流量费用请咨询当地运营商。在使用XXXX前，请认真阅读',
          cencel: '不同意',
          sure: '同意并继续',
          cancelOnTap: () => exit(0),
          sureOnTap: () => SpUtil.putBool('login', true),
        );
      }
    });
    phoneText.text = SpUtil.getString("phone") ?? "";
    passwordText.text = SpUtil.getString("password") ?? "";
  }

  initData() {}

  //点击事件
  initEvent(int tag) async {
    switch (tag) {
      case 0:
        //密码显示隐藏
        obscureText = !obscureText;
        notifyListeners();
        break;
      case 1:
        //注册账号
        Application()
            .navigatePushToPage(me, Routes.registerPage, {"pageTag": 0});
        break;
      case 2:
        //忘记密码
        Application()
            .navigatePushToPage(me, Routes.registerPage, {"pageTag": 1});
        break;
      case 3:
        fluwx.registerWxApi(
            appId: Constant.appId,
            universalLink: "https://your.univerallink.com/link/",
            doOnAndroid: true,
            doOnIOS: true);

        fluwx.isWeChatInstalled.then((value) {
          if (value) {
            fluwx
                .sendWeChatAuth(
                    scope: "snsapi_userinfo", state: "wechat_sdk_demo_test")
                .then((data) {
              fluwx.weChatResponseEventHandler.listen((event) {
                fluwx.WeChatAuthResponse authResponse =
                    event as fluwx.WeChatAuthResponse;
                if (authResponse.errCode == 0) {
                  wxLogin(authResponse.code);
                } else if (authResponse.errCode == -2) {
                  Fluttertoast.showToast(msg: "用户取消");
                } else {
                  print("==========${authResponse.errCode}");
                  Fluttertoast.showToast(msg: "用户拒绝授权");
                }
              });
            }).catchError((e) {
              print("================$e");
            });
          } else {
            Fluttertoast.showToast(
                msg: "请安装微信",
                gravity: ToastGravity.CENTER,
                textColor: Colors.white,
                backgroundColor: Colors.grey);
          }
        });
        break;
      case 4:
        if (phoneText == null || phoneText.text.length != 11) {
          Fluttertoast.showToast(msg: "请输入正确手机号!");
          return;
        }
        if (passwordText == null) {
          Fluttertoast.showToast(msg: "请输入密码!");
          return;
        }
        PromptDialogWidgets(me).showLoadingDialog((Function function) {
          //登录
          DioUtils.getInstance().post(ApiService.lgoin, {
            "phone": phoneText.text,
            "password": passwordText.text,
          }, (successCallBack) {
            function();
            SpUtil.putString("phone", phoneText.text);
            SpUtil.putString("password", passwordText.text);
            xinxiSure(successCallBack);
          }, (errorCallBack) {
            function();
//            Fluttertoast.showToast(msg: "服务器出错");
          });
        });

        break;
    }
  }

  wxLogin(String code) {
    DioUtils.getInstance().post(ApiService.oauthLogin, {
      "app_id": Constant.appId,
      "app_secret": Constant.appSecret,
      "code": code
    }, (successCallBack) {

      Map mapData = successCallBack['data'];
      if (mapData == null) {
        return;
      }

      if (mapData["is_phone"] == 0) {
        Constant.code = mapData['username'];
        Application()
            .navigatePushToPage(me, Routes.registerPage, {"pageTag": 2});
      } else {
        xinxiSure(successCallBack);
      }
    }, (errorCallBack) {});
  }

  xinxiSure(Map successCallBack) {
    SpUtil.putString("role_now", successCallBack["data"]["role_now"] ?? "");
    SpUtil.putString("token", successCallBack["data"]["token"] ?? "");
    DioUtils.getInstance(tag: 1);
    Dio2Utils.getInstance(tag: 1);
    Fluttertoast.showToast(msg: successCallBack["message"]);
    Navigator.pop(me);
    if (successCallBack["data"]["role_now"] == null ||
        successCallBack["data"]["role_now"] == "") {
      Application()
          .navigatePushToPage(me, Routes.switchIdentityPage, {"pageTag": 0});
    } else {
      StudentInformationModel studentInformationModel;
      if (successCallBack["data"]["role_now"] == "TEACHER") {
        if (successCallBack["data"]['student_now'] != null &&
            successCallBack["data"]['student_now'].toString().isNotEmpty) {
          studentInformationModel = StudentInformationModel.fromJsonLogin(
              successCallBack["data"]['student_now']);
        }
        studentInformationModel = StudentInformationModel.fromJsonLogin(
            successCallBack["data"]['cls_now']);
      } else {
        if (successCallBack["data"]['student_now'] != null &&
            successCallBack["data"]['student_now'].toString().isNotEmpty) {
          studentInformationModel = StudentInformationModel.fromJsonLogin(
              successCallBack["data"]['student_now']);
        }
      }
      if (studentInformationModel != null) {
        SpUtil.putString(
            "getStudent", jsonEncode(studentInformationModel.toJson()));
      }
      Application().navigatePushToPage(me, Routes.mainTabPage, {});
    }
  }
}
